<template>
  <div class="view-container">
    <header-module :left-custom="true" :padding="true">
      <template #left-con>
        <span v-if="openForm.agentType === 'agent'">新建推荐代理商</span>
        <span v-if="openForm.agentType === 'agent_person'">新建推荐兼职大包</span>
      </template>
      <template #btn>
        <el-button class="border-btn" size="small" @click="handlBack">返回</el-button>
        <el-button size="small" type="primary" @click="handlSubmit">保存</el-button>
      </template>
    </header-module>

    <div class="main-content">
      <el-form ref="openRef" :model="openForm" :rules="rules" label-width="140px" size="small">
        <el-row gutter="40">

          <el-col :span="24">
            <item-title title="基本信息" />
          </el-col>

          <el-col :span="24">
            <el-form-item label="代理商类型" prop="agentType">
              <el-radio-group v-model="openForm.agentType" :disabled="booleRadio" @change="handlRadio">
                <el-radio label="agent">企业代理</el-radio>
                <el-radio label="agent_person">兼职大包</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item v-if="openForm.agentType === 'agent'" label="代理商名称" prop="agentName">
              <el-autocomplete v-model="openForm.agentName" style="width: 100%" placeholder="请输入代理商名称"
                :fetch-suggestions="querySearchAgent" :loading="false" @select="handleSelecAgent">
                <template #default="{ item }">
                  <div class="distributeName">{{ item.agentName }}</div>
                </template>
              </el-autocomplete>
            </el-form-item>
            <el-form-item v-if="openForm.agentType === 'agent_person'" label="兼职姓名" prop="userName">
              <el-autocomplete v-model="openForm.userName" style="width: 100%" placeholder="请输入兼职人员姓名"
                :fetch-suggestions="querySearchAgent" :loading="false" @select="handleSelecAgent">
                <template #default="{ item }">
                  <div class="distributeName">{{ item.userName }}</div>
                </template>
              </el-autocomplete>
            </el-form-item>
          </el-col>

          <el-col v-if="openForm.agentType === 'agent'" :span="8">
            <el-form-item label="所在地区" prop="value">
              <el-cascader v-model="openForm.value" :popper-append-to-body="false" style="width:100%"
                placeholder="请选择地区" :options="cityList"
                :props="{ value:'regionCode',label:'regionName',expandTrigger: 'hover' }" @change="handlCity" />
            </el-form-item>
          </el-col>

          <el-col v-if="openForm.agentType === 'agent_person'" :span="8">
            <el-form-item label="性别" prop="sex">
              <el-radio-group v-model="openForm.sex">
                <el-radio label="1">男</el-radio>
                <el-radio label="2">女</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>

          <el-col v-if="openForm.agentType === 'agent'" :span="8">
            <el-form-item label="详细地址" prop="address">
              <el-input v-model="openForm.address" clearable placeholder="请输入详细地址" />
            </el-form-item>
          </el-col>

          <el-col v-if="openForm.agentType === 'agent'" :span="8">
            <el-form-item label="联系人" prop="contacts">
              <el-input v-model="openForm.contacts" clearable placeholder="请输入联系人" />
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="联系电话" prop="tel">
              <el-input v-model="openForm.tel" clearable placeholder="请输入联系电话" />
            </el-form-item>
          </el-col>

          <el-col v-if="openForm.agentType === 'agent'" :span="8">
            <el-form-item label="统一社会信用代码" prop="socialCreditNo">
              <el-input v-model="openForm.socialCreditNo" clearable placeholder="请输入统一社会信用代码" />
            </el-form-item>
          </el-col>

          <el-col v-if="openForm.agentType === 'agent_person'" :span="8">
            <el-form-item label="联系地址" prop="address" :required="openForm.agentType === 'agent'">
              <el-input v-model="openForm.address" clearable placeholder="请输入联系地址" />
            </el-form-item>
          </el-col>

          <el-col v-if="openForm.agentType === 'agent_person'" :span="8">
            <el-form-item label="身份证" prop="cardNumber">
              <el-input v-model="openForm.cardNumber" clearable placeholder="请输入身份证号码" />
            </el-form-item>
          </el-col>

          <el-col v-if="openForm.agentType === 'agent_person'" :span="24">
            <el-form-item label="身份证附件" prop="cardFiles">
              <div class="qualityFiles-container">
                <div v-for="(item,index) in openForm.cardFiles" :key="index" class="file-item">
                  <image-upload-view ref="imageUploadView" :data="item" />
                </div>
              </div>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <item-title title="意向代理业务" />
          </el-col>

          <el-col :span="20">
            <el-form-item label="代理产品" prop="productDescribe">
              <div class="box">
                <div style="width: calc(100% - 15px)">
                  <span v-for="(item,index) in openForm.productDescribe" :key="item.id">
                    <template v-if="item.productName">
                      <span> {{ item.productName }}</span>
                      <span class="iconfont icon-shanchu1" style="color: red;cursor:pointer;"
                        @click="handlDele(index,'productDescribe')" />
                      <span v-if="index !== openForm.productDescribe.length - 1"> 、</span>
                    </template>

                  </span>
                </div>
                <div style="width: 15px">
                  <span class="iconfont icon-bianji1 main-color" style="cursor:pointer;" @click="handOpenProduct" />
                </div>

              </div>
            </el-form-item>
          </el-col>

          <el-col :span="4">
            <el-form-item label-width="0px">
              <el-button type="text" @click="handlProduct">选择产品</el-button>
            </el-form-item>
          </el-col>

          <el-col :span="20">
            <el-form-item label="代理地区" prop="area">
              <el-cascader ref="cascader" v-model="openForm.area" clearable style="width: 100%;"
                :popper-append-to-body="false" :options="cityList" placeholder="请选择代理地区" collapse-tags
                :props="{ multiple: true, expandTrigger: 'hover', label: 'regionName', value:'regionCode' }"
                @change="handlArea" />
            </el-form-item>
          </el-col>

          <el-col :span="20">
            <el-form-item label="代理属性" prop="agentIntentionAttribute">
              <el-checkbox-group v-model="openForm.agentIntentionAttribute" @change="handlGroup">
                <el-checkbox v-for="(item,index) in agentAttribute" :key="index" :label="item.value">
                  {{ item.label }}
                </el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row v-if="boole" gutter="40">
          <el-col :span="20">
            <el-form-item label="代理终端" prop="terminalName">
              <div class="box">
                <div style="width: calc(100% - 15px)">
                  <span v-for="(item,index) in openForm.terminalName" :key="item.id">
                    <template v-if="item.terminalName">
                      <span> {{ item.terminalName }}</span>
                      <span class="iconfont icon-shanchu1" style="color: red;cursor:pointer;"
                        @click="handlDele(index,'terminalName')" />
                      <span v-if="index !== openForm.terminalName.length - 1"> 、</span>
                    </template>
                  </span>
                </div>
                <div style="width: 15px">
                  <span class="iconfont icon-bianji1 main-color" style="cursor:pointer; " @click="handlOpenTerminal" />
                </div>

              </div>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label-width="0px">
              <el-button type="text" @click="handlTerminal">选择终端</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

    </div>
    <product ref="productRef" @succsessProduct="succsessProduct" />
    <terminal ref="terminalRef" @succsess="succsess" />
  </div>
</template>

<script>
import {
  defineAsyncComponent,
  getCurrentInstance,
  inject,
  onMounted,
  reactive,
  toRefs,
} from "vue";
import area from "@/utils/area";
import { validateVETel } from "@/utils/validate";
import { useRoute, useRouter } from "vue-router";
import { crmStore } from "@CRM/store";
import areaCode from "@/utils/areaCode.js";

export default {
  name: "Create",
  components: {
    terminal: defineAsyncComponent(() =>
      import("@CRM/views/baseInfo/customer/agent/modules/terminal.vue")
    ),
    product: defineAsyncComponent(() => import("./product.vue")),
  },
  setup() {
    //* ************自定义效验**********
    const validateTel = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入手机码"));
      } else {
        if (validateVETel(value)) {
          callback(new Error("手机号格式不正确"));
        } else {
          callback();
        }
      }
    };
    const validateName = async (rule, value, callback) => {
      if (value === "") {
        callback("请输入代理商名称");
      } else {
        const aaa = await validateVEName(value);
        if (aaa) {
          callback(new Error("代理商名称已存在"));
        } else {
          callback();
        }
      }
    };
    const validateAddress = (rule, value, callback) => {
      if (value === "") {
        callback();
      } else {
        callback();
      }
    };
    //* ********************************
    const api = inject("api");
    const currentInstance = getCurrentInstance();
    const router = useRouter();
    const route = useRoute();
    const data = reactive({
      openBoole: false,
      cityList: area,
      openForm: {
        agentIntentionAttribute: [],
        value: null,
        area: [],
        agentNumber: "",
        agentNo: "",
        agentId: 0,
        agentName: "", // 代理商名称
        provinceCode: "", // 省code
        cityCode: "", // 市code
        areaCode: "", // 区code
        address: "", // 详细地址
        contacts: "", // 联系人
        userName: "", // 兼职人
        userId: 0,
        tel: "", // 联系电话
        socialCreditNo: "", // 统一信用代征码
        agentType: route.query.type ? route.query.type : "agent",
        sex: "1",
        cardNumber: "",
        cardFiles: JSON.parse(
          JSON.stringify(
            crmStore.getters["jsonData/getJsonData"][
              "part_person_qualification"
            ].data || []
          )
        ),
        list: [],
        region: [],
        terminalName: [],
        productDescribe: [],
        planDetailId: route.query.id ? route.query.id : 0,
      },
      openRef: null,
      rules: {
        agentType: [
          { required: true, message: "请选择代理商类型", trigger: "change" },
        ],
        agentName: [
          { required: true, message: "请输入代理商名称", trigger: "change" },
        ],
        address: [{ validator: validateAddress, trigger: "blur" }],
        contacts: [
          { required: true, message: "请输入联系人", trigger: "blur" },
        ],
        userName: [
          { required: true, message: "请输入兼职人员", trigger: "blur" },
        ],
        tel: [{ required: true, validator: validateTel, trigger: "blur" }],
        value: [{ required: true, message: "请选择地区", trigger: "change" }],
        socialCreditNo: [{ message: "请输入统一信用代码", trigger: "blur" }],
      },
      refAddAgent: null,
      index: -1,
      agentAttribute:
        crmStore.getters["dictionary/getDictionary"]["agentAttribute"],
      terminalRef: null,
      cascader: null,
      productRef: null,
      boole: false,
      booleRadio: !!route.query.type,
    });

    const handlRadio = (val) => {
      data.openRef.clearValidate();
      data.openRef.resetFields();
      data.openForm.productDescribe = [];
      data.openForm.area = [];
      data.openForm.agentIntentionAttribute = [];
      data.openForm.terminalName = [];
      data.openForm.agentType = val;
      if (route.query.id) {
        handlDetails(route.query.id);
      }
    };

    const querySearchAgent = async (queryString, cb) => {
      const a = {
        keyWord: queryString,
        agentType: data.openForm.agentType,
      };
      const res = await api.editorial.EDITORIAL_KEYWORDS(a);
      let results = [];
      if (res.code === 0) {
        results = res.data.list || [];
      }
      cb(results);
    };

    const handleSelecAgent = (val) => {
      if (data.openForm.agentType === "agent") {
        data.openForm.agentName = val.agentName;
        data.openForm.agentNo = val.agentNumber;
        data.openForm.agentId = val.id;
        data.openForm.value = [val.provinceCode, val.cityCode, val.areaCode];
        data.openForm.provinceCode = val.provinceCode;
        data.openForm.cityCode = val.cityCode;
        data.openForm.areaCode = val.areaCode;
        data.openForm.address = val.address;
        data.openForm.contacts = val.userName;
        data.openForm.tel = val.tel;
        data.openForm.socialCreditNo = val.creditCode;
      }
      if (data.openForm.agentType === "agent_person") {
        data.openForm.userName = val.userName;
        data.openForm.userId = val.id;
        data.openForm.agentNo = val.agentNumber;
        data.openForm.sex = val.sex;
        data.openForm.tel = val.tel;
        data.openForm.address = val.address;
        data.openForm.cardNumber = val.cardNumber;
        data.openForm.cardFiles = val.cardFiles;
      }
    };

    const handlCity = (val) => {
      if (val) {
        data.openForm.provinceCode = val[0];
        data.openForm.cityCode = val[1];
        data.openForm.areaCode = val[2];
      }
    };

    const handlArea = (val) => {
      data.openForm.area = val;
      data.openForm.region = currentInstance.proxy.getServeAreaData(
        val,
        data.cascader.getCheckedNodes()
      );
    };

    const handlProduct = () => {
      data.productRef.open(data.openForm.productDescribe);
    };

    const handOpenProduct = () => {
      currentInstance.proxy
        .promptInput({ message: "请输入产品" })
        .then(({ value }) => {
          currentInstance.proxy.customMessage({
            type: "success",
            message: "你的输入产品是: " + value,
          });
          const a = {
            productName: value,
            productId: 0,
            ifSelect: false,
          };
          data.openForm.productDescribe.push(a);
        })
        .catch(() => {});
    };

    const handlDetails = (id) => {
      api.plan.PLAN_DETAIL_DETAIL(id).then((res) => {
        if (!res.code) {
          const details = res.data;
          const a = currentInstance.proxy.getProductName(details.planDetail);

          const b = {
            productName: a,
            productId: details.planDetail.productId,
            ifSelect: true,
          };

          data.openForm.productDescribe = [b];
          if (details.planInfo.planType === "2") {
            if (details.planDetail.provinceCode === "") {
              data.openForm.area = areaCode[details.planDetail.cityCode];
            }

            if (details.planDetail.cityCode === "") {
              data.openForm.area = areaCode[details.planDetail.provinceCode];
            }

            if (details.planDetail.areaCode !== "") {
              data.openForm.area = [
                details.planDetail.provinceCode,
                details.planDetail.cityCode,
                details.planDetail.areaCode,
              ];
            }
          }
          if (details.planInfo.planType === "1") {
            if (details.planDetail.terminalProvince === "") {
              data.openForm.area = areaCode[details.planDetail.terminalCity];
            }

            if (details.planDetail.terminalCity === "") {
              data.openForm.area =
                areaCode[details.planDetail.terminalProvince];
            }

            if (details.planDetail.terminalArea !== "") {
              data.openForm.area = [
                details.planDetail.terminalProvince,
                details.planDetail.terminalCity,
                details.planDetail.terminalArea,
              ];
            }
          }

          setTimeout(() => {
            handlArea(data.openForm.area);
          }, 3000);

          data.openForm.agentIntentionAttribute = [
            details.planInfo.planType === "2" ? "1" : "2",
          ];
          handlGroup(data.openForm.agentIntentionAttribute);
          const c = {
            terminalName: details.planDetail.terminalName,
            terminalId: details.planDetail.terminalId,
            ifSelect: true,
          };
          data.openForm.terminalName =
            details.planDetail.terminalName !== "" ? [c] : [];
        } else {
          currentInstance.proxy.customMessage({
            type: "error",
            message: res.msg,
          });
        }
      });
    };

    const handlTerminal = () => {
      const list = {
        terminalList: data.openForm.terminalName.filter((a) => a.id !== 0),
        area: [],
        region: data.cityList,
      };
      data.terminalRef.open(list);
    };

    const handlOpenTerminal = () => {
      currentInstance.proxy
        .promptInput({ message: "请输入终端" })
        .then(({ value }) => {
          currentInstance.proxy.customMessage({
            type: "success",
            message: "你的输入终端是: " + value,
          });
          const a = {
            terminalName: value,
            terminalId: 0,
            ifSelect: false,
          };
          data.openForm.terminalName.push(a);
        })
        .catch(() => {});
    };

    const handlGroup = (val) => {
      if (val.indexOf("2") !== -1) {
        data.boole = true;
      } else {
        data.boole = false;
        data.openForm.terminalName = [];
      }
    };

    const handlDele = (index, key) => {
      data.openForm[key].splice(index, 1);
    };

    const succsessProduct = (val) => {
      const a = [...data.openForm.productDescribe, ...val];
      data.openForm.productDescribe = handlUnique(a, "productId");
    };

    const succsess = (val) => {
      const a = [...data.openForm.terminalName, ...val];
      data.openForm.terminalName = handlUnique(a, "terminalId");
    };

    const handlUnique = (arr, id) => {
      const res = new Map();
      return arr.filter((arr) => !res.has(arr[id]) && res.set(arr[id], 1));
    };

    const handlBack = () => {
      router.go(-1);
    };

    const handlSubmit = () => {
      data.openRef.validate((valid) => {
        if (valid) {
          const obj = {
            agentId: data.openForm.agentId,
            agentName: data.openForm.agentName,
            agentNo: data.openForm.agentNo,
            provinceCode: data.openForm.provinceCode,
            cityCode: data.openForm.cityCode,
            areaCode: data.openForm.areaCode,
            address: data.openForm.address,
            socialCreditNo: data.openForm.socialCreditNo,
            agentType: data.openForm.agentType,
            contacts: data.openForm.contacts,
            tel: data.openForm.tel,
            productDescribe: JSON.stringify(data.openForm.productDescribe),
            region: data.openForm.region,
            agentIntentionAttribute: data.openForm.agentIntentionAttribute,
            terminalName: JSON.stringify(data.openForm.terminalName),
            planDetailId: Number(data.openForm.planDetailId),
            cardNumber: data.openForm.cardNumber,
            cardFiles: data.openForm.cardFiles,
            userName: data.openForm.userName,
            userId: data.openForm.userId,
            sex: data.openForm.sex,
          };

          handlCommint("EDITORIAL_CREATE", obj);
        }
      });
    };

    const handlCommint = (val, obj) => {
      api.editorial[val](obj).then((res) => {
        if (res.code === 0) {
          currentInstance.proxy.customMessage({
            type: "success",
            message: "创建成功",
          });
          handlBack();
        } else {
          currentInstance.proxy.customMessage({
            type: "error",
            message: res.msg,
          });
        }
      });
    };

    onMounted(() => {
      if (route.query.id) {
        handlDetails(route.query.id);
      }
    });

    return {
      ...toRefs(data),
      handlArea,
      handlTerminal,
      handlOpenTerminal,
      handOpenProduct,
      succsess,
      handlDele,
      handlProduct,
      succsessProduct,
      handlCity,
      handlBack,
      handlSubmit,
      handlCommint,
      handlUnique,
      querySearchAgent,
      handleSelecAgent,
      handlGroup,
      handlRadio,
      handlDetails,
    };
  },
};
</script>

<style scoped>
.box {
  width: 100%;
  box-sizing: border-box;
  min-height: 44px;
  padding: 5px 15px;
  border: 1px solid #c0c4cc;
  border-radius: 4px;
  display: flex;
  justify-content: space-between;
}
</style>
